import datetime
import json
import requests
from openpyxl import load_workbook
import yaml


class TestHttps:
    # 姓名
    MY_NAME = "唐磊"
    # 用户名 工号
    USERNAME = 80007380
    # 密码
    PASSWORD = 'z3mDy8aYdhtACzagcGlXZw=='
    # accessToken
    ACCESS_TOKEN = ''
    # 文件地址
    WORK_DATA_EXCEL_FILE_PATH = 'D:/aa/workdata.xlsx'
    # 项目
    PROJECT_ID = 'YZD2021000102'
    PROJECT_NAME = '新华资产组合管理平台项目'
    CUSTOMER_NAME = '新华资产管理股份有限公司'
    CONTRACT_ID = 'BJBX2021358'
    # 任务
    TASK_ID = 'TASK006'
    TASK_DESCRIPTION = '开发-后端开发'
    # 项目开始、结束日期
    PROJECT_START_TIME = '2022-02-01'
    PROJECT_END_TIME = '2023-08-31'

    # 文件日期列 一般不需要修改
    TASK_DATE_INDEX = 2
    # 文件工时列  一般不需要修改
    WORKING_HOURS_INDEX = 3
    # 登录地址
    LOGIN_URL = 'http://180.167.198.186:6521/api/auth-center/jwt/login'
    # 新增地址
    ADD_URL = 'http://180.167.198.186:6521/api/amc-datalink-server/custom-view/add'
    # 数据查询地址
    DATA_QUERY_URL = 'http://180.167.198.186:6521/api/amc-datalink-server/custom-view/custom-list'
    # 提交地址
    SUBMIT_URL = 'http://180.167.198.186:6521/api/amc-datalink-server/custom-view/edit'
    # viewid
    viewId = "yss0292C081291D42052FA9E5CCB681A8A0"

    @staticmethod
    def readConfig():
        with open('config.yaml', 'r', encoding='utf-8') as f:
            return yaml.load(f.read(), Loader=yaml.FullLoader)  # 其返回一个字典数据

    @classmethod
    def configClassField(self):
        config = TestHttps.readConfig()
        self.MY_NAME = config.get('MY_NAME')
        self.USERNAME = config.get('USERNAME')
        self.PASSWORD = config.get('PASSWORD')

        # 文件地址
        self.WORK_DATA_EXCEL_FILE_PATH = config.get('WORK_DATA_EXCEL_FILE_PATH')
        # 项目
        self.PROJECT_ID = config.get('PROJECT_ID')
        self.PROJECT_NAME = config.get('PROJECT_NAME')
        self.CUSTOMER_NAME = config.get('CUSTOMER_NAME')

        self.CONTRACT_ID = config.get('CONTRACT_ID')
        # 任务
        self.TASK_ID = config.get('TASK_ID')
        self.TASK_DESCRIPTION = config.get('TASK_DESCRIPTION')
        # 项目开始、结束日期
        self.PROJECT_START_TIME = config.get('PROJECT_START_TIME')
        self.PROJECT_END_TIME = config.get('PROJECT_END_TIME')

        # 文件日期列 一般不需要修改
        self.TASK_DATE_INDEX = config.get('TASK_DATE_INDEX')
        # 文件工时列  一般不需要修改
        self.WORKING_HOURS_INDEX = config.get('WORKING_HOURS_INDEX')
        # 登录地址
        self.LOGIN_URL = config.get('LOGIN_URL')
        print("读取用户配置完成：" + str(config))

    @classmethod
    def testHttpPost(self):
        workDate= []
        self.configClassField()
        headers = {
            'Authorization': self.getAuthoriztion()}
        url = 'http://180.167.198.186:6521/api/amc-datalink-server/custom-view/add'
        addWorkDataReqJsonList = self.getReqJsonDataList()
        # print(addWorkDataReqJsonList)
        succuss_count = 0
        succuss_time = 0
        fail_count = 0
        fail_time = 0
        for reqJson in addWorkDataReqJsonList:
            dataJsonStr = json.dumps(reqJson)
            rep = requests.post(self.ADD_URL, data=dataJsonStr, headers=headers)
            workDate.append(reqJson.get("TASK_DATE"))
            print(reqJson.get("TASK_DATE") + " : " + str(reqJson.get("WORKING_HOURS")) + " -> " + json.loads(
                rep.text).get("code"))

            if "ok" == str(json.loads(rep.text).get("code")):
                succuss_count += 1
                succuss_time += reqJson.get("WORKING_HOURS")
            else:
                fail_count += 1
                fail_time += reqJson.get("WORKING_HOURS")
        print("自动录入工时完毕，成功条数：" + str(succuss_count) + " 成功总工时：" + str(succuss_time) + " 失败条数："
              + str(fail_count) + " 失败总工时：" + str(fail_time))
        return workDate

    # {
    #   "PROJECT_START_TIME": "2022-02-01",
    #   "IS_LOCK": "未锁定",
    #   "DAYS": "1",
    #   "JOB_NUMBER": "80007380",
    #   "CONTRACT_ID": "BJBX2021358",
    #   "BUSINESS_MANAGER": "YSS",
    #   "PROJECT_NAME": "新华资产组合管理平台项目",
    #   "TASK_DESCRIPTION": "开发-后端开发",
    #   "WORKING_HOURS": "10.5",
    #   "PROJECT_MEMBER": "唐磊",
    #   "TASK_DATE": "2023-03-01",
    #   "CUSTOMER_NAME": "新华资产管理股份有限公司",
    #   "NOTE": null,
    #   "id": "SEQ665669177876422154",
    #   "CREATE_TIME": "2023-03-06 15:06:49",
    #   "PROJECT_END_TIME": "2023-08-31",
    #   "PROJECT_ID": "YZD2021000102",
    #   "TASK_ID": "TASK006",
    #   "STAFF_CODE": "80007380,80000013,80010999,YS210006,800002101,80000097,80005962,80001210,80008968,80009924,YS210001,80000003,YS210098,YS210005,80003646,80000383,YS210009,80007685,80000030,80001015,80005161,80005248,80007019,YS210004,80009858,80000457,80000007,80006306,80000253,80000255,80000001,80009054,80000343,80000004,80000002,80006003,80000013,80010999,YS210006,800002101,80000097,80005962,80001210,80008968,80009924,YS210001,80000003,YS210098,YS210005,80003646,80000383,YS210009,80007685,80000030,80001015,80007019,80005248,YS210004,80009858,80000457,80000007,80006306,80000253,80000015,80000255,80000001,80009054,80000343,80000004,80000002",
    #   "status": 0,
    #   "checker": "唐磊",
    #   "checkTime": "2023-03-10 19:53:03",
    #   "viewId": "yss0292C081291D42052FA9E5CCB681A8A0"
    # }

    @classmethod
    def autoSubmit(self, workStartDate, workEndDate):
        submitJsonDataList = self.listNeedSubmitData(workStartDate, workEndDate)
        # 无需重复获取
        # headers = {
        #     'Authorization': self.getAuthoriztion()}
        # for submitJson in submitJsonDataList:
        #     submitJson["viewId"] = self.viewId
        #     submitJson["status"] = 0
        #     submitJsonStr = json.dumps(submitJson)
        #     # print(str(submitJsonStr))
        #     rep = requests.post(self.SUBMIT_URL, data = submitJsonStr, headers = headers)
        #     # print(str(rep.text))
        #     print(submitJson.get("TASK_DATE") + " : " + str(submitJson.get("WORKING_HOURS")) + " -> " + json.loads(
        #         rep.text).get("code"))
        #     # print(submitJson.get("TASK_DATE") + " : " + str(submitJson.get("WORKING_HOURS")) + " -> " + json.loads(
        #     #     rep.text).get("code"))

    @classmethod
    def listNeedSubmitData(self, startDate = '2023-03-01', endDate = '2023-03-02'):
        # 无需重复获取
        print("自动提交开始>>>>>")
        headers = {
            'Authorization': self.getAuthoriztion()}
        value = startDate + "," + endDate
        dataQryReqJson = {
            "page": 1,
            "limit": 100,
            "viewId": "yss0292C081291D42052FA9E5CCB681A8A0",
            "prop": "TASK_DATE;",
            "order": "descending;",
            "variableParameters": [
                {
                    "name": "JOB_NUMBER",
                    "operation": "like",
                    "value": "80007380"
                },
                {
                    "name": "TASK_DATE",
                    "operation": "between",
                    "value": value
                }
            ]
        }
        print(str(dataQryReqJson))
        # dataQryReqJson = self.getDataQryReqJson()
        # rep = requests.post(self.DATA_QUERY_URL, data = json.dumps(dataQryReqJson), headers = headers)
        # return json.loads(rep.text).get("data").get("rows")
        # print(str(json.loads(
        #     rep.text).get("data").get("rows")))

    @classmethod
    def getAuthoriztion(self):
        if len(self.ACCESS_TOKEN) == 0:
            authJson = {
                'username': self.USERNAME,
                'password': self.PASSWORD
            }
            headers = {'Content-Type': 'application/json', 'User-Agent': 'PostmanRuntime/7.26.8'}
            response = requests.post(self.LOGIN_URL, data=json.dumps(authJson), headers=headers)
            responseJson = json.loads(response.text)
            accessToken = responseJson.get("data").get("accessToken")
            print("成功获取accessToken：" + accessToken)
            self.ACCESS_TOKEN = accessToken
            return accessToken
        else:
            return self.ACCESS_TOKEN

    @classmethod
    def getReqJsonDataList(self):
        reqJsonDataList = []
        dataJsonItem = {
            'viewId': 'yss0292C081291D42052FA9E5CCB681A8A0',
            'JOB_NUMBER': '80007380',
            'PROJECT_MEMBER': '唐磊',
            'CUSTOMER_NAME': '赢证',
            'PROJECT_ID': 'YZD2022000107',
            'PROJECT_NAME': '场外交易系统-内部自研',
            'TASK_ID': 'TASK006',
            'BUSINESS_MANAGER': 'YSS',
            'TASK_DATE': '2023-02-01',
            'TASK_DESCRIPTION': '开发-后端开发',
            'WORKING_HOURS': 8,
            'DAYS': 1,
            'NOTE': '',
            'STAFF_CODE': '80007380,80000013,80010999,YS210006,800002101,80000097,80005962,80001210,80008968,80009924,YS210001,80000003,YS210098,YS210005,80003646,80000383,YS210009,80007685,80000030,80001015,80005161,80005248,80007019,YS210004,80009858,80000457,80000007,80006306,80000253,80000255,80000001,80009054,80000343,80000004,80000002,80006003,80000013,80010999,YS210006,800002101,80000097,80005962,80001210,80008968,80009924,YS210001,80000003,YS210098,YS210005,80003646,80000383,YS210009,80007685,80000030,80001015,80007019,80005248,YS210004,80009858,80000457,80000007,80006306,80000253,80000015,80000255,80000001,80009054,80000343,80000004,80000002',
            'PROJECT_START_TIME': '2021-05-14',
            'PROJECT_END_TIME': '2023-12-31',
            'CREATE_TIME': '2023-03-06 15:06:49',
            'IS_LOCK': '未锁定',
            'CONTRACT_ID': '',
            'status': 2,
            'creator': '唐磊',
            'createTime': '2023-03-06 15:08:38'
        }
        # 工时数据list
        # workDateDataList = [{'2023-03-01': 10.5}, {'2023-03-02': 11.5}]
        workDateDataList = self.getWorkDataFromExcel()
        if len(workDateDataList) == 0:
            print('工时数据为空')
            return []
        createTime = datetime.date.strftime(datetime.datetime.today(), "%Y-%m-%d %H:%M:%S")
        for itme in workDateDataList:
            for TASK_DATE in itme.keys():
                dataJsonItem['TASK_DATE'] = TASK_DATE
                dataJsonItem['WORKING_HOURS'] = itme.get(TASK_DATE)
                dataJsonItem['PROJECT_ID'] = self.PROJECT_ID
                dataJsonItem['PROJECT_NAME'] = self.PROJECT_NAME
                dataJsonItem['CUSTOMER_NAME'] = self.CUSTOMER_NAME
                dataJsonItem['CONTRACT_ID'] = self.CONTRACT_ID
                dataJsonItem['TASK_ID'] = self.TASK_ID
                dataJsonItem['TASK_DESCRIPTION'] = self.TASK_DESCRIPTION
                dataJsonItem['PROJECT_START_TIME'] = self.PROJECT_START_TIME
                dataJsonItem['PROJECT_END_TIME'] = self.PROJECT_END_TIME
                dataJsonItem['JOB_NUMBER'] = self.USERNAME
                dataJsonItem['PROJECT_MEMBER'] = self.MY_NAME
                dataJsonItem['creator'] = self.MY_NAME
                dataJsonItem['createTime'] = createTime
                reqJsonDataList.append(dataJsonItem.copy())
        print("组装请求JSON：" + str(reqJsonDataList))
        return reqJsonDataList

    @classmethod
    def getWorkDataFromExcel(self):
        wb = load_workbook(self.WORK_DATA_EXCEL_FILE_PATH)
        sheets = wb.worksheets  # 获取当前所有的sheet
        # 迭代读取所有的自己的列
        workDateDataList = []
        idx = 0
        for row in sheets[0].rows:
            if idx > 0:
                col_val = [item.value for item in row]
                if str(col_val[0]) == str(self.USERNAME):
                    workDateDataList.append({col_val[self.TASK_DATE_INDEX]: col_val[self.WORKING_HOURS_INDEX]})
            idx = idx + 1
        print("获取工时数据成功：" + str(workDateDataList))
        return workDateDataList


if __name__ == '__main__':
    # 读取配置
    # with open('config.yaml', 'r', encoding='utf-8') as f:
    #     result = yaml.load(f.read(), Loader=yaml.FullLoader)
    #
    # 获取验证token
    # accessToken = TestHttps.getAuthoriztion()
    # print(accessToken)
    #
    # 获取请求Json
    # reqJsonDataList = TestHttps.getReqJsonDataList()
    #     print(result)  # 其返回一个字典数据
    # print(reqJsonDataList)

    # excel自动录入工时系统
    http = TestHttps()
    workDate = http.testHttpPost()
    # workDate = ['2023-03-06', '2023-03-07', '2023-03-04', '2023-03-03', '2023-03-01', '2023-03-02']
    workDate.sort()
    # 提交
    http.autoSubmit(workDate[0], workDate[-1])